// packageG/pages/buy/cart_store/cart_store.js
const DrainageScene = require('../../../../utils/drainage_scene.js')
var app = getApp();
var clicktag = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    language: '',
    goodsCarts: {}, //购物车转为goods key的数组
    carts: [], //购物车商品
    cartsNum: 0,
    cartsTotal: 0.0,
    foot_type: "",
    bottom_info: {},
    buttondisab: true,
  },

  _getCartList(){
    let that = this;
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.store.get-store-info.get-stores-details');
    app._getNetWork({
      url: urlStr,
      data: {
        store_id: app.data.storeID,
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.getFirstCart(res.data.member_cart);
        }
      },
      complete: function() {
        wx.hideLoading()
        that.setData({
          buttondisab: true
        });
      }
    })
  },

  getFirstCart(data) {
    this.setData({
      carts: data,
      goodsCarts: [],
      cartsNum: 0,
      cartsTotal: 0
    });
    let arrObj = {};
    this.data.carts.forEach(item => {
      arrObj[item.goods_id] = item;
      this.setData({
        cartsNum: this.data.cartsNum + item.total,
        cartsTotal: this.data.cartsTotal + (item.total * item.goods.price)
      });
    });
    this.setData({
      goodsCarts: arrObj,
      cartsTotal: parseFloat(this.data.cartsTotal).toFixed(2)
    });
  },

  //商品列表 减(弹窗)
  numberLeft1(e) {
    if (!this.data.buttondisab) {
      return;
    }
    wx.showLoading({
      title: '添加商品中'
    });
    this.setData({
      buttondisab: false
    });
    let goodsT = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    if (app._isTextEmpty(goodsT)) {
      this.updateCart(goodsT.id, -1);
    } else {
      this.setData({
        goodsCartsOld: goodsT.total,
        ['carts[' + index + '].total']: Number(goodsT.total) - 1
      });
      clicktag = 0;
      this.updateCart(this.data.carts[index].id, -1);
    }
  },

  //商品列表 加(弹窗)
  numberRight1(e) {
    if (!this.data.buttondisab) {
      return;
    }
    this.setData({
      buttondisab: false
    });
    wx.showLoading({
      title: '添加商品中'
    });
    let goodsT = e.currentTarget.dataset.item;
    let index = e.currentTarget.dataset.index;
    if (app._isTextEmpty(goodsT)) {
      this.addCart(goodsT, "cart");
    } else {
      this.setData({
        goodsCartsOld: goodsT.total,
        ['carts[' + index + '].total']: Number(goodsT.total) + 1
      });
      this.addCart(goodsT, "cart");
    }
  },

  addCart(goods, tag, goodindex, index, foodindex) {
    let that = this;
    let id = "";
    if (tag === "cart") {
      id = goods.goods_id;
    } else {
      id = goods.id;
    }
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.shoppingCart.member-cart.store');
    urlStr += '&goods_id=' + id;
    urlStr += '&total=1';
    urlStr += '&store_id=' + app.data.storeID;
    urlStr += '&option_id=' + (goods.option_id?goods.option_id:0);
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that._getCartList();
        } else {
          that._getCartList();
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },

  updateCart(id, num) {
    console.log(num)
    if (num < 0) {
      var total = 0;
      this.data.carts.forEach(item => {
        console.log(item);
        if (item.id == id) {
          total = item.total;
        }
      });

      if (total + num < 0) {
        if (clicktag === 0) {
          clicktag = 1;
          this.delItemByCart(id);
          setTimeout(function () {
            clicktag = 0;
          }, 500);
        }
        return;
      }
      if (clicktag === 0) {
        clicktag = 1;
        this.updateCartRequest(id, num);
        setTimeout(function () {
          clicktag = 0;
        }, 500);
      }
    } else {
      if (clicktag === 0) {
        clicktag = 1;
        this.updateCartRequest(id, num);
        setTimeout(function () {
          clicktag = 0;
        }, 500);
      }
    }
  },

  delItemByCart(cart_id) {
    let that = this;
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.shoppingCart.member-cart.destroy');
    urlStr += '&store_id=' + app.data.storeID;
    urlStr += '&ids=' + cart_id;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that._getCartList();
          that.setData({
            popNum: that.data.popNum - 1,
            showCart: false
          });
          that.getminicartStyle();
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },

  getminicartStyle() {
    if (this.data.showCart) {
      this.setData({
        minicartStyle: "display: none;transform: translateY(-100%)",
        leftPrice: "transform: translateX(-60px);"
      });
    } else {
      this.setData({
        minicartStyle: "transform: translateY(0)",
        leftPrice: ''
      });
    }
  },

  updateCartRequest(id, num) {
    let that = this;
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.shoppingCart.member-cart.updateNum');
    urlStr += '&id=' + id;
    urlStr += '&num=' + num;
    urlStr += '&store_id=' + app.data.storeID;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (num < 0) {
            that.setData({
              popNum: that.data.popNum - 1
            });
          } else {
            that.setData({
              popNum: that.data.popNum + 1
            });
          }
          that._getCartList();
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
          that._getCartList();
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },

  clearCart() {
    var that = this;
    var destroyCarts = [];
    this.data.carts.forEach(item => {
      destroyCarts.push(item.id);
    });
    let urlStr = app.getNetAddresss('plugin.store-cashier.frontend.shoppingCart.member-cart.destroy');
    urlStr += '&store_id=' + app.data.storeID;
    urlStr += '&ids=' + destroyCarts;
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that._getCartList();
          that.setData({
            showCart: false,
            popNum: 0
          });
          that.getminicartStyle();
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 1500
          });
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },

  //跳转个人中心
  gomember() {
    wx.reLaunch({
      url: '/packageG/member_store/member_store?store_id=' + app.data.storeID
    });
  },
  //跳转到首页
  gohome() {
    wx.reLaunch({
      url: '/packageG/o2o/HomeSeller/HomeSeller?store_id=' + app.data.storeID
    });
  },

  goodsOrder(e) {
    console.log(e);
    let val = e.currentTarget.dataset.goodscarts;
    this._goodsOrder(val);
  },
  _goodsOrder(val, status) {
    let sum = 0;
    if (!status && !this.isHasDifferType(val)) {
      return;
    }
    this.data.carts.forEach(val => {
      sum += val.total;
    });
    if (sum == 0) {
      return;
    }
    if (val.length == 0 || this.data.carts.length == 0) {
      return;
    } else {
      wx.navigateTo({
        url: '/packageD/buy/myOrder_v2/myOrder_v2?tag=store&store_id=' + app.data.storeID
      });
    }
  },

  isHasDifferType(data) {
    //门店购物车提交结算的时候，要判断当前购物车中是否同时存在普通商品和安装服务商品，如果同时存在，要弹框提示
    // 商品不是安装服务商品，直接没有live_install这个字段
    let open_state = 0; //有安装服务的商品
    let clone_state = 0; //没安装服务的商品
    let plugin_name = "";
    for (let item in data) {
      if (item.live_install && item.live_install.open_state == 1) {
        open_state += 1;
        plugin_name = item.live_install.plugin_name;
      } else {
        clone_state += 1;
      }
    }
    if (open_state != 0 && clone_state != 0) {
      //都有值说明存在 两种 不同商品类型，提示框显示
      wx.showModal({
        title: '提示',
        content: `普通商品与${plugin_name}商品一同下单将无法享受${plugin_name}，是否继续下单？`,
        success: (res) => {
          if (res.confirm) {
            this._goodsOrder(data, true);
          } else if (res.cancel) {
            console.log(res.cancel);
          }
        }
      });
      return false;
    }
    return true;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideHomeButton()
    this.getStoreInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
    wx.setNavigationBarTitle({
      title: this.data.language.cart["购物车"]
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this._getCartList()
  },

  getStoreInfo() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.get-store-info.get-the-provider");
    app._getNetWork({
      url: urlStr,
      data: {
        store_id: app.data.storeID,
      },
      success: function(resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          if (res.data.store_decorate && res.data.store_decorate.datas) {
            that.setData({
              foot_type: res.data.store_decorate.foot_type,
            })
            // 装修的底部有三种情况
            if (res.data.store_decorate.foot_type == -1) {
              // 不显示
              this.setData({
                bottom_info: {},
              });
            } else if (res.data.store_decorate.foot_type == 1) {
              // 显示默认
              if (!res.data.store_decorate.foot_id || !res.data.store_decorate.foot_id.page_info) {
                // 显示系统默认
                that.setData({
                  bottom_info: {},
                });
              } else {
                // 显示列表设置的默认
                that.setData({
                  bottom_info: JSON.parse(res.data.store_decorate.foot_id.page_info),
                  showcarrfoot_ipxBol: true
                });
              }
            } else if (res.data.store_decorate.foot_type == 2) {
              // 显示自定义的底部导航
              if (!res.data.store_decorate.foot_id || res.data.store_decorate.foot_id instanceof Array) {
                that.setData({
                  bottom_info: {},
                });
              } else {
                that.setData({
                  bottom_info: JSON.parse(res.data.store_decorate.foot_id.page_info),
                  showcarrfoot_ipxBol: true
                });
              }
            }
          }
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  onShareTimeline:function(){
    
  }
});